const cmds = require('./cmd.js');
function blue_list(func){   
  wx.openBluetoothAdapter({
    success: function (res) {},
    fail: function () { wx.showToast({ title: '请先启用蓝牙功能！', }) },      
    complete:function(){
        console.log("blue_list success");
        var services = getApp().globalData.able_serviceIds;
        wx.startBluetoothDevicesDiscovery({
          services: services,
          success: function () {            
            console.log("蓝牙搜索中1...");
          },
          fail:function(e){
            console.log("蓝牙搜索失败",e);
          }        
        })
    }
  });
  setTimeout(function () { _blu_list(func)},500);      
}


//获取蓝牙列表
function _blu_list(func){  
    var services=getApp().globalData.able_serviceIds;
    //监听蓝牙状态
    wx.onBluetoothAdapterStateChange(function(res){
          if(res.available){
              if(!res.discovering){
                console.log("蓝牙暂停搜索...");
              }
          }else{
            wx.showToast({
              title: '请先启用蓝牙功能！',
            })
          }
    });

  setTimeout(function(){
      //获取设备
      wx.getBluetoothDevices({
        success: function (res) {
          var devices = res.devices;                   
          func(devices);
        },
      })
      //监听新的设备
      wx.onBluetoothDeviceFound(function (res) {
        wx.getBluetoothDevices({
          success: function (e) {
            var devices = e.devices;
            func(devices);
          },
        })
      })
    },500);    
}
//关闭发现
function blue_discovery_close(){
    wx.stopBluetoothDevicesDiscovery({
      success: function (res) {console.log("停止stopBluetoothDevicesDiscovery--success"); },
      fail: function () { console.log("停止stopBluetoothDevicesDiscovery--fail"); },
  })
}
//开启连接
function blue_con(deviceId,func,func1) {
  var app=getApp();
  if (deviceId == null || deviceId == "") {wx.showToast({ title: '请选择deviceId', }); return false;}        
  wx.showLoading({title: '正在连接...',});    
  wx.createBLEConnection({
    deviceId: deviceId,
    success: function (res) {
       wx.hideLoading();
       func(deviceId);       
       console.log("连接成功");      
       getApp().globalData.blue_is_connectd = true;
       //开启异常链接监听
       wx.onBLEConnectionStateChange(function(e){
           console.log('device ' + e.deviceId + ' state has changed, connected: '+e.connected);
           if(!e.connected){
             app.globalData.current_con_deviceId = null;
             wx.showToast({ title: '连接断开', });
             getApp().globalData.blue_is_connectd=false;
           }
       });          
       blue_notify(deviceId, func1);
    },
    fail: function (res) { console.log("连接失败",res); },   
    complete:function(){blue_discovery_close();}  //关闭搜索
  })
}
//关闭连接
function blue_con_close(){
  var app = getApp();
  var deviceId = app.globalData.current_con_deviceId;
  if(deviceId==''||deviceId==null){
    return false;
  }
  wx.closeBLEConnection({
    deviceId: deviceId,
    success: function (res) {
      app.globalData.current_con_deviceId = null;
      console.log("停止closeBLEConnection--success");
    },
    fail: function (res) {
      console.log("停止closeBLEConnection--fail",res);      
    }
  }) 
  wx.closeBluetoothAdapter({
    success: function(res) {},
  })
}
//关闭所有
function blue_close(){    
    blue_con_close();    
}

//发送指令
function blue_write(set1){ 
  var deviceId = getApp().globalData.current_con_deviceId;
  var serviceId = getApp().globalData.current_con_serviceId[0];
  if (deviceId == null || deviceId == '') {
    wx.showToast({ title: '蓝牙连接已经断开', });
    return false;
  }
  
  var charset_write = getApp().globalData.charset_write[0];  
  var charset_notify = getApp().globalData.charset_notify[0];  
  //封装数据  
   var cmd =set1;
  //管道写值
  wx.writeBLECharacteristicValue({
    deviceId: deviceId,
    serviceId: serviceId,
    characteristicId: charset_write,
    value: cmd,
    success: function (res) {           
       console.log("发送指令成功1：", res);  
    },                  
    fail:function(res){  console.log("发送指令失败:",res);}      
  })  
}
//接收通知
function blue_notify(deviceId, func1){
  var serviceId = getApp().globalData.current_con_serviceId[0];
  var charset_notify = getApp().globalData.charset_notify[0];
  var charset_write = getApp().globalData.charset_write[0];  
  //获取服务（一定要运行 否者报1004）
  wx.getBLEDeviceServices({
    deviceId: deviceId,
    success: function (res) {
      wx.getBLEDeviceCharacteristics({
        deviceId: deviceId,
        serviceId: serviceId,
        success: function (e) {        
          
          console.log("获取charset 成功",e);
          //notifyBLECharacteristicValueChange 的监听
          wx.notifyBLECharacteristicValueChange({
            state: true, // 启用 notify 功能
            // 这里的 deviceId 需要在上面的 getBluetoothDevices 或 onBluetoothDeviceFound 接口中获取
            deviceId: deviceId,
            // 这里的 serviceId 需要在上面的 getBLEDeviceServices 接口中获取
            serviceId: serviceId,
            // 这里的 characteristicId 需要在上面的 getBLEDeviceCharacteristics 接口中获取
            characteristicId: charset_notify,
            success: function (res) {
              console.log('charset_notify success:', res);
            },
            fail: function (res) { console.log("charset_notify error:", charset_notify, res) },
            complete: function () { console.log("charset_notify complete"); }
          });



          //onBLECharacteristicValueChange 监听
          wx.onBLECharacteristicValueChange(function (characteristic) {
            console.log('characteristic value changed:', characteristic);
            var buffer = characteristic.value;
            var dataView = new DataView(buffer);
            if (characteristic.characteristicId == charset_write) {
              var len = buffer.byteLength;
              for (var i = 0; i < len; i++) {
                console.log("charset_write change:", i, dataView.getUint8(i));               
              }             
            } else if (characteristic.characteristicId == charset_notify) {
              var len = buffer.byteLength;
              if (len > 2) {
                cmds.gets(buffer, func1);             
              }
              for(var i=0;i<len;i++){
                console.log("charset_notify change:",i, dataView.getUint8(i));                                
              }
            } else {
              func1("检查是  null");
              console.log("检查是  null");
            }
          }); 
        },
        fail: function (e) {
          console.log("获取charset 失败--",e,deviceId,serviceId);          
        }
      })
    },
    fail: function (res) {
      console.log("getBLEDeviceServices---fail",res);// 这个可以判断蓝牙断开      
    }
  }); 
}
//读取管道的值
function blue_read(characteristicId){
  var deviceId = getApp().globalData.current_con_deviceId[0];
  var serviceId = getApp().globalData.current_con_serviceId[0];   
  if(deviceId==null||deviceId==''){
    wx.showToast({
      title: '未链接设备',
    })
    return ;
  }
  wx.readBLECharacteristicValue({
    deviceId: deviceId,
    serviceId: serviceId,
    characteristicId: characteristicId,
    success: function (res) {
      console.log("读取管道的值--success", res);
    },
    fail:function(res){      
      console.log("读取管道的值--fail", res );      
    }
  })  
}
//读取心率数据

module.exports={
  blue_list: blue_list,
  blue_close: blue_close,
  blue_con: blue_con,    
  blue_write: blue_write,  
  blue_read: blue_read  
}